/*
 * **.cpp - 
 *
 * Copyright (C) 2010-2012 Serge Begger
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */


#include "poweroffnotifer.h"

poweroffnotifer::poweroffnotifer(QObject *parent) :
    QObject(parent)
{
    int sock_fd = connectSocket();
    if ( sock_fd < 0) {
        qWarning("Not open acpid.socket");
        return;
    }
    sk = new QSocketNotifier(sock_fd,QSocketNotifier::Read,this);
    connect(sk,SIGNAL(activated(int)),this,SLOT(sigHandler(int)));
    fcntl(sock_fd, F_SETFD, FD_CLOEXEC);
}

void poweroffnotifer::sigHandler(int sock_fd) {
    sk->blockSignals(true);
    char buf[64];
    int r = ::read(sock_fd, buf, sizeof(buf));
    if (r < 0) {
        qWarning("Not read socket");
        return;
    }
    if (QString(buf).compare("button/power"))
        emit pwrOff();
    sk->blockSignals(false);
}

int poweroffnotifer::connectSocket() {

    int fd;
    int r;
    struct sockaddr_un addr;

    fd = ::socket(AF_UNIX, SOCK_STREAM, 0);
    if (fd < 0) {
        return fd;
    }

    memset(&addr, 0, sizeof(addr));
    addr.sun_family = AF_UNIX;
    sprintf(addr.sun_path, "%s", "/var/run/acpid.socket");

    r = ::connect(fd, (struct sockaddr *)&addr, sizeof(addr));
    if (r < 0) {
        ::close(fd);
        return r;
    }

    return fd;
}
